<template>
  <div class="production-pie-wrapper" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'ProductionPie',
  props: {
    chartData: {
      type: Array, // [{name: 'Ehy', value: 83}, {name: 'c71', value: 17}]
      required: true
    }
  },
  data() {
    return {
      colorList: ['#347be6', '#ffb21a']
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    chartData: {
      handler: 'initChart',
      deep: true
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) return;
      if (this.chart) this.chart.dispose();
      this.chart = echarts.init(this.$refs.chartRef);

      this.chart.setOption({
        backgroundColor: 'transparent',
        color: this.colorList,
        legend: {
          orient: 'horizontal',
          bottom: 0,
          left: 'center',
          itemWidth: 14,
          itemHeight: 14,
          textStyle: {
            color: '#fff',
            fontSize: 16
          },
          formatter: name => {
            const item = this.chartData.find(d => d.name === name);
            return name+item.value + '%' // `{a|${name}}  {b|${item ? item.value + '%': ''}}`;
          },
          rich: {
            a: { color: '#fff', fontSize: 16, padding: [0, 2, 0, 0] },
            b: { color: '#fff', fontSize: 16, fontWeight: 'normal' }
          }
        },
        series: [
          {
            type: 'pie',
            radius: ['60%', '80%'],
            center: ['50%', '48%'],
            avoidLabelOverlap: false,
            startAngle: 210,
            minAngle: 10,
            label: {
              show: true,
              position: 'outside',
              color: '#fff',
              fontSize: 16,
              formatter: '{d}%'
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20,
              lineStyle: {
                color: '#fff'
              }
            },
            data: this.chartData,
            itemStyle: {
              borderColor: '#111a2f',
              borderWidth: 4
            }
          }
        ],
        graphic: {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'text',
              left: 'center',
              top: 'middle',
              style: {
                text: '量产\n占比',
                fill: '#8cb6f7',
                font: 'bold 24px Microsoft YaHei',
                textAlign: 'center',
                textVerticalAlign: 'middle'
              }
            }
          ]
        }
      });
    }
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose();
  }
};
</script>

<style scoped>
.production-pie-wrapper {
  width: 100%;
  height: 240px;
  background: transparent;
}
</style>
